#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：刘骏轩2025讯飞 
@File ：SET_GREEN_VAL.py
@Author ：ljx
@Date ：2025/8/7 下午10:35 
"""
import cv2
import numpy as np


# 回调函数，x 表示滑块的位置
def nothing(x):
    pass


def create_Trackbar():
    cv2.namedWindow('Trackbar')

    # 创建 LAB 六个滑动条
    cv2.createTrackbar('L_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('L_MIN', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('A_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('A_MIN', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('B_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('B_MIN', 'Trackbar', 0, 255, nothing)

    # 设置初始值
    cv2.setTrackbarPos('L_MAX', 'Trackbar', 255)
    cv2.setTrackbarPos('L_MIN', 'Trackbar', 0)
    cv2.setTrackbarPos('A_MAX', 'Trackbar', 80)
    cv2.setTrackbarPos('A_MIN', 'Trackbar', 0)
    cv2.setTrackbarPos('B_MAX', 'Trackbar', 255)
    cv2.setTrackbarPos('B_MIN', 'Trackbar', 0)


if __name__ == '__main__':
    create_Trackbar()
    cap = cv2.VideoCapture(0)

    while 1:
        ret, frame = cap.read()
        frame = cv2.flip(frame, 1)

        if not ret:
            continue

        # 获取滑块的值
        l_max = cv2.getTrackbarPos('L_MAX', 'Trackbar')
        l_min = cv2.getTrackbarPos('L_MIN', 'Trackbar')
        a_max = cv2.getTrackbarPos('A_MAX', 'Trackbar')
        a_min = cv2.getTrackbarPos('A_MIN', 'Trackbar')
        b_max = cv2.getTrackbarPos('B_MAX', 'Trackbar')
        b_min = cv2.getTrackbarPos('B_MIN', 'Trackbar')

        lower = np.array([l_min, a_min, b_min])
        upper = np.array([l_max, a_max, b_max])

        cv2.imshow('orign', frame)

        lab_img = cv2.cvtColor(frame, cv2.COLOR_BGR2Lab)
        
        mask = cv2.inRange(lab_img, lower, upper)

        nums = np.count_nonzero(mask == 255)
        cv2.imshow("res",mask)
        print(f"upper:{upper}")
        print(f"lower:{lower}")
        print(f"白色像素点个数{nums}")

        cv2.waitKey(1)
